#include <iostream>
#include "../comm/httplib.h"
#include "control.hpp"
using namespace std;
using namespace httplib;

static Control* ctrl_ptr = nullptr;

void sigheadler(int signo)
{
    ctrl_ptr->RestoreMachine();
}

int main()
{
    Server svr;
    Control ctrl;
    ctrl_ptr = &ctrl;
    signal(SIGQUIT, sigheadler);

    svr.Get("/all_questions", [&ctrl](const Request &req, Response &rep)
    { 
        // 返回所有题目列表的网页
        string html;
        ctrl.AllQuestions(&html);
        
        rep.set_content(html, "text/html; charset=utf-8"); 
    });

    // 正则表达式
    svr.Get(R"(/number_question/(\d+))", [&ctrl](const Request &req, Response &rep)
    { 
        // 返回固定题目网页
        string  number = req.matches[1];
        string html;
        ctrl.OneQuestion(number, &html);
        
        rep.set_content(html, "text/html; charset=utf-8"); 
    });

    svr.Post(R"(/judge/(\d+))", [&ctrl](const Request &req, Response &rep)
    { 
        string number = req.matches[1];
        string out_json;
        ctrl.Judge(number, req.body, &out_json);

        rep.set_content(out_json, "application/json;charset:utf-8"); 
    });

    svr.set_base_dir("./web");
    svr.listen("0.0.0.0", 8080);
    return 0;
}